from uliweb.core.SimpleFrame import expose, Request
from models import TodoFile
from werkzeug import BaseRequest

@expose('/upload_attatch/<id>')
def doto_upload(id):
    Request.max_content_length = settings.UPLOAD.FILESIZE
    
    if request.method == 'POST':
        f = request.files['Filedata']
        from uliweb.contrib.upload import save_file, get_url
        filename = save_file(f.filename, f.stream, replace=True, subfolder='todo/%s' % str(id), application=application)
        
        t = TodoFile.get((TodoFile.c.filename==filename) & (TodoFile.c.todo==int(id)))
        if t:
            status = 'exist'
        else:
            t = TodoFile(filename=filename, todo=int(id), user=request.user)
            t.save()
            status = 'add'
       
        return json({'status':status, 'html':_make_todo_file(t, id)})

def _make_todo_file(t, id):
    return '''<li class="file" id="file_%(id)d"><a href="%(href)s">%(filename)s</a> <img src="%(delete)s" onclick="delete_file(%(todo_id)s, %(id)d)"/></li>
''' % {'filename':t.filename, 'id':t.id, 'href':get_url(t.filename, subfolder="todo/%s" % str(id)),
        'delete':url_for_static('cancel.png'), 'todo_id':str(id)}

@expose('/gettodofiles/<id>')
def doto_get_todofiles(id):
    s = []
    for t in TodoFile.filter(TodoFile.c.todo==int(id)):
        s.append(_make_todo_file(t, id))
    return ''.join(s)
    
@expose('/deletefile')
def doto_delete_file():
    todo_id = request.GET.get('todo_id')
    file_id = request.GET.get('file_id')
    
    TodoFile.remove((TodoFile.c.todo==int(todo_id)) & (TodoFile.c.id==int(file_id)))